#include <iostream>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
void Usage(char *arg)
{
    std::cout << "Usage:" << arg << " ip port" << std::endl;
}

// ./tcpclient ip port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "client socket create error!" << std::endl;
        exit(1);
    }
    sockaddr_in peer;
    inet_pton(AF_INET, ip.c_str(), &peer.sin_addr.s_addr);
    peer.sin_family = AF_INET;
    peer.sin_port = htons(port);
    int n = connect(sockfd, reinterpret_cast<sockaddr *>(&peer), sizeof(peer));
    if (n == 0)
    {
        while (true)
        {
            std::cout << "Please Enter# ";
            char buffer[1024];
            std::cin >> buffer;
            send(sockfd, buffer, sizeof(buffer), 0);
            char outbuffer[1024];
            ssize_t n = recv(sockfd, outbuffer, sizeof(outbuffer), 0);
            std::cout << outbuffer << std::endl;
        }
    }
    return 0;
}